package com.hm.oauth2.auto;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author shishun.wang
 * @date 下午3:07:48 2016年11月18日
 * @version 1.0
 * @describe 授权服务器 <note>2.授权服务器
 *           授权服务器是一个负责验证凭据，如果凭据都行，提供令牌[刷新令牌以及访问令牌。它还包含有关注册客户和可能的访问范围和授权类型的信息。
 *           令牌存储用于存储的令牌。我们将使用一个内存令牌存储。@EnableAuthorizationServer使一个授权服务器（
 *           即一个AuthorizationEndpoint和TokenEndpoint）在当前的应用程序上下文。
 *           类AuthorizationServerConfigurerAdapter工具AuthorizationServerConfigurer提供所有必要的方法来配置授权服务器。
 *           </note>
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

	private final static String REALM = "MY_OAUTH_REALM";

	@Autowired
	private TokenStore tokenStore;

	@Autowired
	private UserApprovalHandler userApprovalHandler;

	@Autowired
	@Qualifier("authenticationManagerBean")
	private AuthenticationManager authenticationManager;

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory().withClient("my-trusted-client")
				.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
				.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT").scopes("read", "write", "trust").secret("secret")
				.accessTokenValiditySeconds(120).// Access token is only valid
													// for 2 minutes.
				refreshTokenValiditySeconds(600);// Refresh token is only valid
													// for 10 minutes.

		// 注册一个客户端，客户端ID“我信任的客户端'和密码'秘密'，他是允许的角色和范围。
		// 指定任何生成的访问令牌的有效期只有120秒
		// 指定任何生成刷新令牌的有效期只有600秒
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
				.authenticationManager(authenticationManager);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		security.realm(REALM + "/client");
	}
}
